using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Chat.Backend.Services.Media
{
    /// <summary>
    /// 表情包服务 - 处理表情包的存储、获取和使用
    /// </summary>
    public class EmojiService : IEmojiService
    {
        private readonly ILogger<EmojiService> _logger;
        private readonly IEmojiRepository _emojiRepository;
        private readonly IUserEmojiRepository _userEmojiRepository;
        private readonly IStorageService _storageService;
        private readonly EmojiSettings _settings;

        /// <summary>
        /// 构造函数
        /// </summary>
        public EmojiService(
            ILogger<EmojiService> logger,
            IEmojiRepository emojiRepository,
            IUserEmojiRepository userEmojiRepository,
            IStorageService storageService,
            IOptions<EmojiSettings> settings)
        {
            _logger = logger;
            _emojiRepository = emojiRepository;
            _userEmojiRepository = userEmojiRepository;
            _storageService = storageService;
            _settings = settings.Value;
        }

        /// <summary>
        /// 获取系统表情包分类列表
        /// </summary>
        public async Task<List<EmojiCategory>> GetSystemEmojiCategoriesAsync()
        {
            try
            {
                return await _emojiRepository.GetEmojiCategoriesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统表情包分类失败");
                throw;
            }
        }

        /// <summary>
        /// 获取分类下的表情包列表
        /// </summary>
        public async Task<List<Emoji>> GetEmojisByCategoryAsync(string categoryId)
        {
            try
            {
                return await _emojiRepository.GetEmojisByCategoryAsync(categoryId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取分类表情包失败: 分类ID {categoryId}");
                throw;
            }
        }

        /// <summary>
        /// 获取用户收藏的表情包
        /// </summary>
        public async Task<List<Emoji>> GetUserFavoriteEmojisAsync(string userId)
        {
            try
            {
                // 获取用户收藏的表情包ID列表
                var favoriteIds = await _userEmojiRepository.GetUserFavoriteEmojiIdsAsync(userId);
                
                // 根据ID列表获取表情包详情
                var emojis = new List<Emoji>();
                foreach (var id in favoriteIds)
                {
                    var emoji = await _emojiRepository.GetEmojiByIdAsync(id);
                    if (emoji != null)
                    {
                        emojis.Add(emoji);
                    }
                }
                
                return emojis;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户收藏表情包失败: 用户ID {userId}");
                throw;
            }
        }

        /// <summary>
        /// 获取用户自定义表情包
        /// </summary>
        public async Task<List<Emoji>> GetUserCustomEmojisAsync(string userId)
        {
            try
            {
                return await _userEmojiRepository.GetUserCustomEmojisAsync(userId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户自定义表情包失败: 用户ID {userId}");
                throw;
            }
        }

        /// <summary>
        /// 添加表情包到收藏
        /// </summary>
        public async Task AddEmojiToFavoritesAsync(string userId, string emojiId)
        {
            try
            {
                // 检查表情包是否存在
                var emoji = await _emojiRepository.GetEmojiByIdAsync(emojiId);
                if (emoji == null)
                {
                    throw new ArgumentException($"表情包不存在: {emojiId}");
                }
                
                // 添加到收藏
                await _userEmojiRepository.AddEmojiToFavoritesAsync(userId, emojiId);
                
                _logger.LogInformation($"用户 {userId} 收藏表情包 {emojiId}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加表情包到收藏失败: 用户ID {userId}, 表情包ID {emojiId}");
                throw;
            }
        }

        /// <summary>
        /// 从收藏中移除表情包
        /// </summary>
        public async Task RemoveEmojiFromFavoritesAsync(string userId, string emojiId)
        {
            try
            {
                await _userEmojiRepository.RemoveEmojiFromFavoritesAsync(userId, emojiId);
                
                _logger.LogInformation($"用户 {userId} 取消收藏表情包 {emojiId}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从收藏中移除表情包失败: 用户ID {userId}, 表情包ID {emojiId}");
                throw;
            }
        }

        /// <summary>
        /// 创建自定义表情包
        /// </summary>
        public async Task<Emoji> CreateCustomEmojiAsync(string userId, byte[] imageData, string name)
        {
            try
            {
                // 上传表情包图片
                var fileName = $"emoji_{userId}_{Guid.NewGuid()}.png";
                var url = await _storageService.UploadFileAsync(imageData, "emojis", fileName, "image/png");
                
                // 创建表情包记录
                var emoji = new Emoji
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = name,
                    Url = url,
                    Type = EmojiType.Custom,
                    CreatorId = userId,
                    CreateTime = DateTime.UtcNow
                };
                
                // 保存到用户自定义表情包
                await _userEmojiRepository.SaveCustomEmojiAsync(userId, emoji);
                
                _logger.LogInformation($"用户 {userId} 创建自定义表情包 {emoji.Id}");
                
                return emoji;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建自定义表情包失败: 用户ID {userId}");
                throw;
            }
        }

        /// <summary>
        /// 删除自定义表情包
        /// </summary>
        public async Task DeleteCustomEmojiAsync(string userId, string emojiId)
        {
            try
            {
                // 获取表情包信息
                var emoji = await _userEmojiRepository.GetCustomEmojiAsync(userId, emojiId);
                if (emoji == null)
                {
                    throw new ArgumentException($"自定义表情包不存在或不属于该用户: {emojiId}");
                }
                
                // 删除表情包记录
                await _userEmojiRepository.DeleteCustomEmojiAsync(userId, emojiId);
                
                // 删除表情包文件
                if (!string.IsNullOrEmpty(emoji.Url))
                {
                    try
                    {
                        // 从URL中提取文件路径
                        var uri = new Uri(emoji.Url);
                        var path = uri.AbsolutePath;
                        if (!string.IsNullOrEmpty(path))
                        {
                            await _storageService.DeleteFileAsync(path);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"删除表情包文件失败: {emoji.Url}");
                    }
                }
                
                _logger.LogInformation($"用户 {userId} 删除自定义表情包 {emojiId}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除自定义表情包失败: 用户ID {userId}, 表情包ID {emojiId}");
                throw;
            }
        }

        /// <summary>
        /// 发送表情包消息
        /// </summary>
        public async Task<MessageResult> SendEmojiMessageAsync(string senderId, string receiverId, string emojiId, bool isGroupChat = false)
        {
            try
            {
                // 获取表情包信息
                Emoji emoji = null;
                
                // 先查找系统表情包
                emoji = await _emojiRepository.GetEmojiByIdAsync(emojiId);
                
                // 如果不是系统表情包，尝试查找用户自定义表情包
                if (emoji == null)
                {
                    emoji = await _userEmojiRepository.GetCustomEmojiAsync(senderId, emojiId);
                }
                
                if (emoji == null)
                {
                    throw new ArgumentException($"表情包不存在: {emojiId}");
                }
                
                // 创建表情包消息对象
                var emojiMessage = new EmojiMessageContent
                {
                    EmojiId = emoji.Id,
                    EmojiUrl = emoji.Url,
                    EmojiName = emoji.Name,
                    IsCustom = emoji.Type == EmojiType.Custom
                };
                
                // 序列化为JSON
                var content = System.Text.Json.JsonSerializer.Serialize(emojiMessage);
                
                // 创建消息对象
                var message = new ChatMessage
                {
                    Id = Guid.NewGuid().ToString(),
                    SenderId = senderId,
                    ReceiverId = receiverId,
                    Content = content,
                    Type = MessageType.Emoji,
                    IsGroupChat = isGroupChat,
                    SendTime = DateTime.UtcNow,
                    Status = MessageStatus.Sending
                };
                
                // 保存消息到数据库
                await _chatRepository.SaveMessageAsync(message);
                
                // 构建消息体
                var messageBody = new ChatMessageBody
                {
                    MessageId = message.Id,
                    Type = "emoji",
                    Content = content,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(messageBody);
                
                // 发送XMPP消息
                var xmppTo = isGroupChat 
                    ? $"{receiverId}@conference.{_xmppService.Domain}" 
                    : $"{receiverId}@{_xmppService.Domain}";
                
                var messageType = isGroupChat ? MessageType.GroupChat : MessageType.Chat;
                
                await _xmppService.SendMessageAsync(xmppTo, messageJson, messageType);
                
                // 更新消息状态
                message.Status = MessageStatus.Sent;
                await _chatRepository.UpdateMessageStatusAsync(message.Id, MessageStatus.Sent);
                
                return new MessageResult
                {
                    Success = true,
                    MessageId = message.Id
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送表情包消息失败: 从 {senderId} 到 {receiverId}, 表情包ID {emojiId}");
                return new MessageResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }
    }

    /// <summary>
    /// 表情包服务接口
    /// </summary>
    public interface IEmojiService
    {
        Task<List<EmojiCategory>> GetSystemEmojiCategoriesAsync();
        Task<List<Emoji>> GetEmojisByCategoryAsync(string categoryId);
        Task<List<Emoji>> GetUserFavoriteEmojisAsync(string userId);
        Task<List<Emoji>> GetUserCustomEmojisAsync(string userId);
        Task AddEmojiToFavoritesAsync(string userId, string emojiId);
        Task RemoveEmojiFromFavoritesAsync(string userId, string emojiId);
        Task<Emoji> CreateCustomEmojiAsync(string userId, byte[] imageData, string name);
        Task DeleteCustomEmojiAsync(string userId, string emojiId);
        Task<MessageResult> SendEmojiMessageAsync(string senderId, string receiverId, string emojiId, bool isGroupChat = false);
    }
}